package com.example.bmchandlerdemo;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = "MainActivity";
    private BluetoothAdapter mBtAdapter;
    BluetoothDevice _device = null;   //蓝牙设备
    BluetoothSocket _socket = null;   //蓝牙通信socket
    private final static String MY_UUID = "00001101-0000-1000-8000-00805F9B34FB";   //SPP服务UUID号
    private InputStream is;    //输入流，用来接收蓝牙数据
    boolean bThread = false;
    public String receiveData = "";
    boolean isReceiving = false;
    private boolean isLinerConnect = false;
    private TextView mTvMax;
    private TextView mTvCur;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initBluetooth();
        initView();
    }

    private void initView() {
        findViewById(R.id.btn_connect).setOnClickListener(this);
        findViewById(R.id.btn_correct).setOnClickListener(this);
        findViewById(R.id.btn_start_collect).setOnClickListener(this);
        findViewById(R.id.btn_stop_collect).setOnClickListener(this);
        findViewById(R.id.btn_get_version).setOnClickListener(this);

        mTvMax = findViewById(R.id.tv_max);
        mTvCur = findViewById(R.id.tv_cur);
    }

    private boolean initBluetooth() {
        // 得到本地蓝牙句柄
        mBtAdapter = BluetoothAdapter.getDefaultAdapter();

        //如果打开本地蓝牙设备不成功，提示信息，结束程序
        if (mBtAdapter == null) {
            Toast.makeText(this, "无法打开手机蓝牙，请确认手机是否有蓝牙功能！", Toast.LENGTH_LONG).show();
            finish();
            return true;
        }

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
        intentFilter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
        intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
        getApplicationContext().registerReceiver(mReceiver, intentFilter);
        return false;
    }

    // 查找到设备和搜索完成action监听器
    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Log.e(TAG, action);
            if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
                int blueState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0);
                switch (blueState) {
                    case BluetoothAdapter.STATE_ON:
                        connectLiner();
                        break;
                }
            }
            // 查找到设备action
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                // 得到蓝牙设备
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                Log.d(TAG, "蓝牙设备：" + device.getName());
                if (device != null && device.getName() != null) {
                    if (device.getName().equals("HC-02")) {
                        connectSBY(device.getAddress());
                    }
                }
                // 搜索完成action
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                if (_socket != null) {
                    return;
                }
                //                dialog.dismiss();
                Toast.makeText(MainActivity.this, "找不到识别仪，请检查设备是否开启！", Toast.LENGTH_LONG).show();


            } else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
                Toast.makeText(MainActivity.this, "识别仪已断开", Toast.LENGTH_LONG).show();
                closeSocket();


            }
        }
    };

    private void closeSocket() {
        try {
            if (is != null) {
                is.close();
            }
            if (_socket != null) {
                _socket.close();
            }
            _socket = null;
            _device = null;
            bThread = false;

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void connectSBY(String address) {
        mBtAdapter.cancelDiscovery();
        // 得到蓝牙设备句柄
        _device = mBtAdapter.getRemoteDevice(address);
        try {
            _socket = _device.createRfcommSocketToServiceRecord(UUID.fromString(MY_UUID));
            _socket.connect();
            Toast.makeText(this, "连接识别仪成功！", Toast.LENGTH_SHORT).show();
            isLinerConnect = true;
            mBtAdapter.cancelDiscovery();

            is = _socket.getInputStream();   //得到蓝牙数据输入流
            if (bThread == false) {
                readThread.start();
                bThread = true;
            }
        } catch (IOException e) {
            try {
                Toast.makeText(this, "连接失败,请重试", Toast.LENGTH_SHORT).show();
                _socket.close();
                _socket = null;
            } catch (IOException ee) {
                Toast.makeText(this, "连接失败,请重试", Toast.LENGTH_SHORT).show();
            }
        }

    }

    //接收数据线程
    Thread readThread = new Thread() {

        public void run() {
            //接收线程
            while (true) {
                try {
                    while (true) {
                        if (!bThread)//跳出循环
                            return;
                        oldReceive();
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    };


    private void oldReceive() throws IOException {
        int num = 0;
        byte[] buffer = new byte[1024];
        byte[] buffer_new = new byte[1024];
        int i = 0;
        int n = 0;
        num = is.read(buffer);         //读入数据
        n = 0;
        String s0 = new String(buffer, 0, num);
        for (i = 0; i < num && i < 1024; i++) {
            if ((buffer[i] == 0x0d) && (buffer[i + 1] == 0x0a)) {
                buffer_new[n] = 0x0a;
                i++;
            } else {
                buffer_new[n] = buffer[i];
            }
            n++;
        }
        String s = new String(buffer_new, 0, n);
        Log.d(TAG, "recevice:" + s);
        String[] strArr = s.split("\n");
        for (String string : strArr) {
            if (string.contains("STOP_CORRECT")) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this, "校准完成", Toast.LENGTH_LONG).show();
                    }
                });
            } else if (string.endsWith("@VAL")) {
                String str = string;
                receiveData = receiveData + str + "\n";
                str = str.replace("@VAL", "");
                final String[] arr = str.split("@");
                if (arr.length == 2) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mTvMax.setText("最大值：" + arr[0].trim());
                            mTvCur.setText("当前值：" + arr[1].trim());
                        }
                    });
                }
            } else if (string.contains("CODE_")) {
                final String code = string;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this, code, Toast.LENGTH_SHORT).show();
                    }
                });
            }
        }

    }

    @Override
    protected void onDestroy() {
        // 关闭服务查找
        if (mBtAdapter != null) {
            mBtAdapter.cancelDiscovery();
        }
        try {
            getApplicationContext().unregisterReceiver(mReceiver);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //        dialog = null;
        mBtAdapter = null;
        _socket = null;
        _device = null;
        is = null;

        super.onDestroy();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_connect:
                connectLiner();
                break;
            case R.id.btn_correct:
                btn_correctClick();
                break;
            case R.id.btn_start_collect:
                btn_start_collectClick();
                break;
            case R.id.btn_stop_collect:
                btn_stop_collectClick();
                break;
                case R.id.btn_get_version:
                    getVersion();
                    break;
        }
    }

    public void getVersion() {
        if (!onSendButtonClicked("GET_VERSION")) {

        }
    }

    /**
     * 开始识别
     */
    public void btn_start_collectClick() {
        receiveData = "";
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                onSendButtonClicked("APP_START_COLLECT");
            }
        }, 500);
    }

    /**
     * 停止识别
     */
    public void btn_stop_collectClick() {
        if (!onSendButtonClicked("APP_STOP_COLLECT")) {
            return;
        }
    }

    /**
     * 开始校准
     */
    public void btn_correctClick() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                onSendButtonClicked("APP_START_CORRECT");
            }
        }, 500);
    }

    //发送按键响应
    public boolean onSendButtonClicked(String msg) {
        Log.d(TAG, "onSendButtonClicked:" + msg);
        boolean isConnected = false;
        if ((_socket != null && _socket.isConnected())) {
            if (_device != null && _device.getName() != null && _device.getName().equals("HC-02")) {
                isConnected = true;
            }
        }

        if (!isConnected) {
            Toast.makeText(this, "请先连接设备", Toast.LENGTH_SHORT).show();
            return false;
        }

        int i = 0;
        int n = 0;
        if (_socket == null) {
            Toast.makeText(this, "请先连接蓝牙模块", Toast.LENGTH_SHORT).show();
        } else {
            if (_device != null && _device.getName() != null && _device.getName().equals("HC-02")) {
                try {
                    Log.e("MAIN_SEND", msg);
                    OutputStream os = _socket.getOutputStream();   //蓝牙连接输出流
                    byte[] bos = msg.getBytes();
                    for (i = 0; i < bos.length; i++) {
                        if (bos[i] == 0x0a) {
                            n++;
                        }
                    }
                    byte[] bos_new = new byte[bos.length + n];
                    n = 0;
                    for (i = 0; i < bos.length; i++) { //手机中换行为0a,将其改为0d 0a后再发送
                        if (bos[i] == 0x0a) {
                            bos_new[n] = 0x0d;
                            n++;
                            bos_new[n] = 0x0a;
                        } else {
                            bos_new[n] = bos[i];
                        }
                        n++;
                    }


                    os.write(bos_new);
                } catch (IOException e) {
                }
            }
        }
        return true;
    }

    /**
     * 连接和断开识别仪
     */
    private void connectLiner() {
        if (isLinerConnect) {
            disconnectBluetooth();
        } else {
            connectBluetooth();
        }
    }

    /**
     * 连接蓝牙
     */
    private void connectBluetooth() {
        if (_socket != null) {//当前有连接蓝牙

        } else {//当前没有连接蓝牙
            if (mBtAdapter.isEnabled() == false) {  //如果蓝牙服务不可用则提示
                //                dialog.show();
                Toast.makeText(MainActivity.this, "正在连接，请稍等", Toast.LENGTH_SHORT).show();
                mBtAdapter.enable();
                return;
            } else {
                Toast.makeText(MainActivity.this, "正在连接，请稍等", Toast.LENGTH_SHORT).show();
                doDiscovery();
            }
        }
    }

    /**
     * 开始服务和设备查找
     */
    private void doDiscovery() {
        // 关闭再进行的服务查找
        if (mBtAdapter.isDiscovering()) {
            mBtAdapter.cancelDiscovery();
        }

        mBtAdapter.startDiscovery();
    }

    /**
     * 断开蓝牙
     */
    private void disconnectBluetooth() {
        //关闭连接socket
        if (_device != null) {
            Toast.makeText(MainActivity.this, " 断开识别仪中...", Toast.LENGTH_SHORT).show();
        }
        closeSocket();
    }
}
